var mqtt = require("mqtt");

//连接到 MQTT 服务器
const client = mqtt.connect("http://localhost:1883", {
  username: "admin", //用户名
  password: "123456", //密码
  clientId: "1", //客户端id
  connectTimeout: 4000, // 超时时间
  reconnectPeriod: 4000, // 重连间隔时间
});

//订阅主题
client.on("connect", function () {
  client.subscribe("success", function (err) {
    if (!err) {
      console.log("Subscribed to success");
    }
  });
});

//处理收到的消息
client.on("message", function (topic, message) {
  if (topic === "success") {
    console.log("Received message:", message.toString());
  }
});

//重连提醒
client.on("reconnect", (error) => {
  console.log("正在重连", error);
});

//连接失败提醒
client.on("error", (error) => {
  console.log("连接失败", error);
});

//发布消息
setInterval(() => {
  client.publish("myMsg", "123123");
}, 2000);
